package com.util;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.StringTokenizer;
import java.util.Vector;

import javax.servlet.http.HttpServletRequest;

import com.sql.DBFactory;

public class PageDisplay {

	private Connection conn = null;

	private Statement stmt = null;

	private ResultSet rs = null;

	Vector RowClick = new Vector();

	private boolean noData = false;

	private int pageStart;

	private int pageSize;

	private int totalPage;

	private int totalRecord;

	private int columnCount;

	private int currentPageSize;

	private String qdSQL;

	public String URL;

	private java.util.Vector bottomBtn = new java.util.Vector();

	private int startRecord, endRecord;

	public PageDisplay() {
		this.tableBorder = "0";
		this.tableBgcolor = "#dc6b0e";
		this.tableCellpadding = "2";
		this.tableCellspacing = "1";
		this.tableFirstRowBgcolor = "#dc6b0e";
		this.tableLastRowBgcolor = "#FFFFFF";
		this.tableRowcolor1 = "#FFFFFF";
		this.tableRowcolor2 = "#E0E0E0";
		this.tableAlign = "center";
		this.otherArg = "";

	}

	public void getData() {

	}

	/**
	 * 添加横向点击链接
	 */
	@SuppressWarnings("unchecked")
	public boolean addRowClick(String indexID, String lable, String target)
			throws NumberFormatException {
		try {
			@SuppressWarnings("unused")
			java.lang.Integer test = new Integer(indexID);
		} catch (Exception ex) {
			throw new NumberFormatException("indexID 要为整数");
		}

		String[] aClick = new String[3];
		aClick[0] = indexID;
		aClick[1] = lable;
		aClick[2] = target;
		this.RowClick.addElement(aClick);
		return true;
	}

	@SuppressWarnings("unchecked")
	public String[][] getRowClick() {
		String[][] rowClick = new String[this.RowClick.size()][3];
		this.RowClick.toArray(rowClick);
		return rowClick;
	}

	@SuppressWarnings("unchecked")
	public boolean addBottomClick(String btnLable, String target, String arg) {
		String tmpString = "";
		tmpString += "<a href=\"";
		tmpString += target + arg;

		tmpString += "\">";

		tmpString += btnLable;
		tmpString += "</a>" + "&nbsp;";
		this.bottomBtn.addElement(tmpString);
		return true;
	}

	@SuppressWarnings("unchecked")
	public String getBottomClick() {
			String tmpString = "";
		String[] tmpBtn = new String[this.bottomBtn.size()];
		this.bottomBtn.toArray(tmpBtn);
		for (int i = 0; i < this.bottomBtn.size(); i++) {
			tmpString += tmpBtn[i];

		}
		return tmpString;
	}

	// 统计
	public String getStatistic() {

		String sta = intl_di + this.getPageStart() + intl_yegong
				+ this.getTotalPage() + intl_yegong2 + this.getTotalRecord()
				+ intl_tiaojilu;
		return sta;
	}

	// 上下页导航
	public String getNav() {
		String First, Previous, Next, Last, statistic, GotoPage;

		statistic = this.getStatistic();

		GotoPage = "<td align=\"right\" class=\"pt9\">"
				+ intl_GotoText
				+ " <input name=\"GotoPage\" type=\"text\" size=\"2\" class=\"smbutton\"></td><td align=\"left\">"
				+ "<img src=\"" + this.intl_GotoImage
				+ "\" border=\"0\" onclick=\"gotopage('" + this.getOtherArg()
				+ "')\" style=\"CURSOR: hand\"></td>";

		First = (pageStart == 1) ? intl_firstpage + "&nbsp;" : "<A HREF=\""
				+ this.URL + "?pageStart=1&pageSize=" + pageSize
				+ this.getOtherArg() + "\">" + intl_firstpage + "</A>&nbsp;";
		Previous = (pageStart == 1) ? intl_previouspage + "&nbsp;"
				: "<A HREF=\"" + this.URL + "pageStart=" + (pageStart - 1)
						+ "&pageSize=" + pageSize + this.getOtherArg() + "\">"
						+ intl_previouspage + "</A>&nbsp;";
		Next = (pageStart >= totalPage) ? intl_nextpage + "&nbsp;"
				: "<A HREF=\"" + this.URL + "pageStart=" + (pageStart + 1)
						+ "&pageSize=" + pageSize + this.getOtherArg() + "\">"
						+ intl_nextpage + "</A>&nbsp;";
		Last = (pageStart >= totalPage) ? intl_lastpage + "&nbsp;"
				: "<A HREF=\"" + this.URL + "pageStart=" + totalPage
						+ "&pageSize=" + pageSize + this.getOtherArg() + "\">"
						+ intl_lastpage + "</A>&nbsp;";
		String Nav = "";

		if (this.totalRecord <= this.currentPageSize) {
			Nav = "";
		} else {
			Nav = "<table width=\"100%\"><tr align=\"center\"><td>" + First
					+ Previous + statistic + Next + Last + GotoPage
					+ "</td></tr></table>";
		}
		return Nav;
	}

	public boolean init(HttpServletRequest request, int pageStart,
			int pageSize, String sql) {

		this.URL = request.getRequestURI();
		this.pageSize = ((request.getParameter("pageSize") != null) ? Integer
				.parseInt(request.getParameter("pageSize")) : pageSize);
		this.pageStart = (request.getParameter("pageStart") != null) ? Integer
				.parseInt(request.getParameter("pageStart")) : pageStart;
		return this.init(this.pageStart, this.pageSize, sql);

	}

	public boolean init(HttpServletRequest request, int pageStart,
			int pageSize, String sql, String URL) {

		this.URL = URL;
		this.pageSize = ((request.getParameter("pageSize") != null) ? Integer
				.parseInt(request.getParameter("pageSize")) : pageSize);
		this.pageStart = (request.getParameter("pageStart") != null) ? Integer
				.parseInt(request.getParameter("pageStart")) : pageStart;
				
		return this.init(this.pageStart, this.pageSize, sql);

	}

	// 初始化各参数，统计记录数
	public boolean init(int pageStart, int pageSize, String sql) {
		this.pageSize = pageSize;
		this.pageStart = pageStart;
		this.qdSQL = sql;
		try {
			conn = DBFactory.getConnection();
			stmt = conn.createStatement();
			String mytmp = sql;
			rs = stmt.executeQuery(mytmp);
			this.totalRecord = 0;
			while (rs.next()) {
				this.totalRecord++;
			}
			if (this.totalRecord <= 0) {
				this.noData = true;
				return false; 
			}
			if (this.totalRecord % this.pageSize > 0) {
				this.totalPage = this.totalRecord / this.pageSize + 1;
			} else {
				this.totalPage = this.totalRecord / this.pageSize;
			}
			if (this.pageStart < 1) {
				this.pageStart = 1;
			}
			if (this.pageStart > this.totalPage) {
				this.pageStart = this.totalPage;
			}
			if (this.totalPage == 0) {
				this.pageStart = 1;
			}
			// 结束记录数
			this.startRecord = (this.pageStart - 1) * this.pageSize;
			this.endRecord = this.pageStart * this.pageSize;
			if (this.endRecord > this.totalRecord) {
				this.endRecord = this.totalRecord;
			}
			this.currentPageSize = this.endRecord - this.startRecord;
		} catch (Exception ex) {
			return false;
		} finally {
			try {
				stmt.close();
				conn.close();

			} catch (Exception ex) {
			}
		}

		return true;
	}

	public String list() {
		String RString = "";
		java.lang.StringBuffer listString = new java.lang.StringBuffer();

		try {
			conn = DBFactory.getConnection();
			stmt = conn.createStatement();
			String mytmp = this.qdSQL;
			rs = stmt.executeQuery(mytmp);
			ResultSetMetaData rsmd = rs.getMetaData();
			columnCount = rsmd.getColumnCount();
			StringTokenizer t=new StringTokenizer(mytmp,"'");
			if (this.beginTableTag) {

				listString.append("<SCRIPT language=javascript>");
				listString.append("function formreset() { ");
				listString.append("delfrm.reset();");
				listString.append("return;}");
				listString.append("</SCRIPT>");

				if (this.getShowForm()) {
					listString
							.append("<form name=\"delfrm\" method=\"post\" action=\""
									+ this.getFormAction()
									+ "\" onsubmit=\"return delit()\">");
				} else {
					listString.append("<form name=\"delfrm\">");
				}
				listString.append("<table  width=100% border=\""
						+ this.getTableBorder() + "\"");
				listString.append(" cellspacing=\""
						+ this.getTableCellspacing() + "\"");
				listString.append(" cellpadding=\""
						+ this.getTableCellpadding() + "\"");
				listString
						.append(" bgcolor=\"" + this.getTableBgcolor() + "\"");
				listString.append(" class=\"pt9\"");
				listString.append(" align=\"" + this.getTableAlign()
						+ "\">\r\n");
			}
			
			if (titleFlag) {
				listString.append("  <tr align=\"center\" bgcolor=\""
						+ this.getTableFirstRowBgcolor() + "\">\r\n");
				for (int i = 1; i < columnCount; i++) {
					if(t.hasMoreTokens()){
					String tmp =t.nextToken();
					if(t.hasMoreTokens())
					{tmp=t.nextToken();
					//System.out.println(tmp);
					listString.append("    <td >");
					listString.append(tmp);
					listString.append("</td>\r\n");
					}
					}
				}
				if (this.getShowForm()) {
					listString.append("<td>" + FormTitle + "</td>");
				}
				listString.append("  </tr>\r\n");
			}

			for (int i = 0; i < this.startRecord; i++) {
				rs.next();
			}
			if (this.noData) {
				listString.append("  <tr  bgcolor=\"#F6F6F6\">\r\n");
				listString.append("<td align=\"center\" colspan=\""
						+ this.columnCount + "\">\r\n");
				listString.append("暂时没有相关数据。");
				listString.append("</td>\r\n");
				listString.append("  </tr>\r\n");
			}
			for (int ii = 0; ii < this.currentPageSize; ii++) {
				rs.next();
				if (ii % 2 == 0) {
					listString.append("  <tr  bgcolor=\""
							+ this.getTableRowcolor1() + "\">\r\n");
				} else {
					listString.append("  <tr  bgcolor=\""
							+ this.getTableRowcolor2() + "\">\r\n");
				}

				String pk = rs.getString(1);
				for (int i = 2; i <= columnCount; i++) {
					listString.append("<td>");
					String ls = rs.getString(i);
					ls = (ls == null) ? "" : ls;
					String rowClick[][] = this.getRowClick();
					String tmpClick = ls;
					for (int j = 0; j < this.RowClick.size(); j++) {
						int clickCol = Integer.parseInt(rowClick[j][0]);
						if (i == clickCol + 1) {
							tmpClick = "<a href=\"" + rowClick[j][2] + pk
									+ "\"" + rowClick[j][1] + ">" + ls + "</a>";
							break;

						}
					}
					listString.append(tmpClick);
					listString.append("</td>\r\n");
				}
				if (this.getShowForm()) {
					listString
							.append("<td><input type=\"checkbox\" name=\"deleted\" value=\""
									+ rs.getString(this.GetCheckboxValues())
									+ "\"" + Check + "></td>");
				}
				listString.append("  </tr>\r\n");
			}
			if (this.bottomBtn.size() != 0) {
				listString.append("  <tr align=\"right\" bgcolor=\""
						+ this.getTableRowcolor1() + "\">\r\n");
				listString.append("   <td colspan=\"" + this.columnCount
						+ "\">");
				listString.append(this.getBottomClick());
				listString.append("   </td>\r\n");
				listString.append("  </tr>\r\n");
			}

			if (this.bottomRowFlag) {
				listString.append("  <tr hight=\"2\" bgcolor=\""
						+ this.getTableBgcolor() + "\">\r\n");
				listString.append("   <td>");
				listString.append("   </td>\r\n");
				listString.append("  </tr>\r\n");

				listString.append("  <tr align=\"right\" bgcolor=\""
						+ this.getTableLastRowBgcolor() + "\">\r\n");
				listString.append("   <td colspan=\"" + this.columnCount
						+ "\">");
				listString.append(this.getNav());
				listString.append("   </td>\r\n");
				listString.append("  </tr>\r\n");
			}
			if (this.getShowForm()) {
				listString.append("  <tr align=\"center\" bgcolor=\""
						+ this.getTableLastRowBgcolor() + "\">\r\n");
				listString.append("   <td colspan=\"" + this.columnCount
						+ "\">");
				listString.append(FormTitleImage);
				listString.append(Reselect);
				listString.append(SelectAll);
				listString.append("<input type=\"hidden\" name=\"v1\">");
				listString.append("   </td>\r\n");
				listString.append("  </tr>\r\n");
			}
			listString.append("</table>\r\n");
			listString.append("</form>");

			rs.close();
			stmt.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			try {
				stmt.close();
				conn.close();
			} catch (Exception ex) {
			}
		}

		RString = listString.toString();
		return RString;

	}

	public int getPageStart() {
		return pageStart;
	}

	public int getTotalPage() {
		return totalPage;
	}

	public int getTotalRecord() {
		return totalRecord;
	}

	public void setTableBgcolor(String tableBgcolor) {
		this.tableBgcolor = tableBgcolor;
	}

	public String getTableBgcolor() {
		return tableBgcolor;
	}

	public void setTableBorder(String tableBorder) {
		this.tableBorder = tableBorder;
	}

	public String getTableBorder() {
		return tableBorder;
	}

	public void setTableCellpadding(String tableCellpadding) {
		this.tableCellpadding = tableCellpadding;
	}

	public String getTableCellpadding() {
		return tableCellpadding;
	}

	public void setTableCellspacing(String tableCellspacing) {
		this.tableCellspacing = tableCellspacing;
	}

	public String getTableCellspacing() {
		return tableCellspacing;
	}

	public void setTableFirstRowBgcolor(String tableFirstRowBgcolor) {
		this.tableFirstRowBgcolor = tableFirstRowBgcolor;
	}

	public String getTableFirstRowBgcolor() {
		return tableFirstRowBgcolor;
	}

	public void setTableLastRowBgcolor(String tableLastRowBgcolor) {
		this.tableLastRowBgcolor = tableLastRowBgcolor;
	}

	public String getTableLastRowBgcolor() {
		return tableLastRowBgcolor;
	}

	public void setTableRowcolor1(String tableRowcolor1) {
		this.tableRowcolor1 = tableRowcolor1;
	}

	public String getTableRowcolor1() {
		return tableRowcolor1;
	}

	public void setTableRowcolor2(String tableRowcolor2) {
		this.tableRowcolor2 = tableRowcolor2;
	}

	public String getTableRowcolor2() {
		return tableRowcolor2;
	}

	public void setTableAlign(String tableAlign) {
		this.tableAlign = tableAlign;
	}

	public String getTableAlign() {
		return tableAlign;
	}

	public void setOtherArg(String otherArg) {
		this.otherArg = otherArg;
	}

	public String getOtherArg() {
		return otherArg;
	}

	public void setTitleFlag(boolean titleFlag) {
		this.titleFlag = titleFlag;
	}

	public boolean isTitleFlag() {
		return titleFlag;
	}

	public void setBeginTableTag(boolean beginTableTag) {
		this.beginTableTag = beginTableTag;
	}

	public boolean isBeginTableTag() {
		return beginTableTag;
	}

	public void setBottomRowFlag(boolean bottomRowFlag) {
		this.bottomRowFlag = bottomRowFlag;
	}

	public boolean isBottomRowFlag() {
		return bottomRowFlag;
	}

	public void setFormAction(String formaction) {
		this.FormAction = formaction;
	}

	public void setFormAction(String formaction, String formtitle) {
		this.FormAction = formaction;
		this.FormTitle = formtitle;

	}

	public void setFormTitleImage(String newFormTitleImage) {
		this.FormTitleImage = newFormTitleImage;
	}

	public int GetCheckboxValues() {
		return CheckboxValues;
	}

	public void SetCheckboxValues(int NewCheckboxValues) {
		this.CheckboxValues = NewCheckboxValues;
	}

	public void setCheck(String check) {
		this.Check = check;
	}

	public String getFormAction() {
		return FormAction;
	}

	// 是否显示列表的form及删除按扭与checkbox
	public void setShowForm(boolean newShowForm) {
		this.ShowForm = newShowForm;
	}

	public boolean getShowForm() {
		return ShowForm;
	}

	static String intl_di = "第";

	static String intl_yegong = "页/共";

	static String intl_yegong2 = "页 共";

	static String intl_tiaojilu = "条记录";

	static String intl_GotoText = "直接进入页面";

	private String intl_GotoImage = "../images/go.gif"; // goto图片

	static String intl_firstpage = "<img src=\"../images/firstpage.gif\" border=\"0\">"; // 首页

	static String intl_previouspage = "<img src=\"../images/001.jpg\" border=\"0\">"; // 上一页

	static String intl_nextpage = "<img src=\"../images/002.jpg\" border=\"0\">"; // 下一页

	static String intl_lastpage = "<img src=\"../images/lastpage.gif\" border=\"0\">"; // 尾页

	static String SelectAll = "<img src=\"../images/selectall.gif\" onClick=\"selectidall()\" style=\"CURSOR: hand\"><input name=\"showAndCancel\" type=\"hidden\" id=\"showAndCancel\" value=\"show\">"; // 全选按纽

	static String Reselect = "<img src=\"../images/reselect.gif\" onClick=\"formreset()\" style=\"CURSOR: hand\">"; // 重选按纽

	private int CheckboxValues = 1;

	private String tableBgcolor;

	private String tableBorder;

	private String tableCellpadding;

	private String tableCellspacing;

	private String tableFirstRowBgcolor;

	private String tableLastRowBgcolor;

	private String tableRowcolor1;

	private String tableRowcolor2;

	private String tableAlign;

	private String otherArg;

	private String FormAction;

	private String FormTitle = "选项";

	private String FormTitleImage = "<input name=\"del\" type=\"image\" src=\"../images/del.gif\" >";

	private String Check = "";

	private boolean ShowForm = true;

	private boolean titleFlag = true;

	private boolean beginTableTag = true;

	private boolean bottomRowFlag = true;

}
